package cn.dckeji.dcssm.common.utils;

import cn.dckeji.dcssm.common.model.ResultModel;
import cn.hutool.json.JSONObject;
import cn.hutool.setting.dialect.Props;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 上传七牛空间图片工具类 <br>
 * 创建日期：2018-04-13 <br>
 * <b>Copyright 2017 dianChaung property in copyright </b>
 * 
 * @author WangDongdong
 * @since 1.0
 * @version 1.0
 */
public class QiNiuUpLode {

	private static Props props = new Props("config.properties", "utf-8");
	private static String fileName = props.getStr("qi_niu_file_name");
	private static String filePath = props.getStr("qi_niu_file_path");
	private static String url = props.getStr("qi_niu_url");
	private static String accessKey = props.getStr("qi_niu_access_key");
	private static String secretKey = props.getStr("qi_niu_secret_key");
	private static String bucketName = props.getStr("qi_niu_bucket_name");
	private static String serverLode = props.getStr("server_file_url_path");

	public static Auth getAuto(){
		return Auth.create(accessKey, secretKey);
	}

	public static String getToken(){
		return getAuto().uploadToken(bucketName);
	}


    /** 删除文件
     *
     * @since 1.0
     * @param filePath 只是文件名
     * @return
     * <br><b>作者： @author WangDong</b>
     * <br>创建时间：2017-12-7 下午1:42:08
     */
    public static boolean delete(String filePath) {
    	Auth auth = getAuto();
		//构造一个带指定Zone对象的配置类
		Configuration configuration = new Configuration(Zone.zone0());
        // 实例化一个BucketManager对象
        BucketManager bucketManager = new BucketManager(auth,configuration);
        // 要测试的空间和key，并且这个key在你空间中存在
       // String bucket = PublicCode.BUCKET_NAME;
        try {
            // 调用delete方法移动文件
            bucketManager.delete(bucketName, filePath);
            System.err.println("七牛文件删除成功! fileName="+filePath);
            return true;
        } catch (QiniuException e) {
            // 捕获异常信息
            Response r = e.response;
        	System.err.println("七牛文件删除失败! fileName="+filePath);
            System.err.println(r.toString());
            return false;
        }
        
    }


	/**
	 * 上传附件到七牛
	 * @param filePath
	 * @return
	 * @throws IOException
	 */

	public static String  uploadFileToQiNiu(String  filePath) throws IOException {
		//构造一个带指定Zone对象的配置类
		// zone0   华东机房相关域名   //zone1   华北机房相关域名
		//zone2   华南机房相关域名    //zoneNa0   北美机房相关域名
		Configuration configuration = new Configuration(Zone.zone0());
		UploadManager uploadManager = new UploadManager(configuration);
		// 调用put方法上传
		Response res = uploadManager.put(filePath, StringUtil.qiNiuUrl(6)+".png", getToken());
		// 打印返回的信息
		JSONObject jsonObject = new JSONObject(res.bodyString());
		StringBuffer buffer = new StringBuffer();
		buffer.append(url).append(jsonObject.get("key").toString());
		String filename = buffer.toString();
		return filename;
	}


	/**
	 * 上传附件到七牛
	 * @param file
	 * @return
	 * @throws IOException
	 */

	public static Object uploadFileToQiNiu(MultipartFile[] file) throws IOException {
		List<Map> listImagePath=new ArrayList<>();
		for (MultipartFile partFile:file){
			if (!partFile.isEmpty()){

				Map<String,Object> map = StringUtil.getFileName(fileName,filePath,partFile);
				String fileNames =(String) map.get(fileName);
				//默认不指定filePath的情况下，以文件内容的hash值作为文件名
				String filePaths =(String) map.get(filePath);
				InputStream inputStream = partFile.getInputStream();
				//构造一个带指定Zone对象的配置类
				// zone0   华东机房相关域名   //zone1   华北机房相关域名
				//zone2   华南机房相关域名    //zoneNa0   北美机房相关域名
				Configuration configuration = new Configuration(Zone.zone0());
				// 创建上传对象
				UploadManager uploadManager = new UploadManager(configuration);
				// 调用put方法上传
				Response res = uploadManager.put(inputStream, filePaths, getToken(),null,null);
				LinkedHashMap<String,String> hashMap  = new LinkedHashMap<>();
				hashMap.put(fileName,fileNames);
				hashMap.put(filePath,url+filePaths);
				listImagePath.add(hashMap);
			}
		}

		return ResultModel.success(listImagePath);
	}



	/**
	 * 上传附件到本地
	 * @param file
	 * @param request
	 * @return
	 * @throws IOException
	 */

	public  static Object uploadFile(MultipartFile[] file, HttpServletRequest request) throws IOException {
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://"
				+ request.getServerName() + ":" + request.getServerPort()
				+ path + "/";

		String domin = basePath+serverLode;
		//获得webapp所在的物理路径
		String realPath = request.getSession().getServletContext().getRealPath("/"+serverLode);
		//判断上传目录是否存在
		File files = new File(realPath);
		if (!files.exists()){
			files.mkdir();
		}
		List<Map> listImagePath=new ArrayList<>();
		for (MultipartFile partFile:file){
			if (!partFile.isEmpty()){
				Map<String,Object> map = StringUtil.getFileName(fileName,filePath,partFile);
				String fileNames = (String) map.get(fileName);
				String filePaths = (String) map.get(filePath);
				partFile.transferTo(new File(realPath+filePath));

				LinkedHashMap<String,String> hashMap  = new LinkedHashMap<>();
				hashMap.put(fileName,fileNames);
				hashMap.put(filePath,domin+filePaths);
				listImagePath.add(hashMap);
			}
		}

		return   ResultModel.success(listImagePath);
	}

	/**
	 * 删除七牛旧图
	 * @param newUrl
	 * @param oldUrl
	 * @return
	 */
	public  boolean delQiNiuOldPic(String newUrl,String oldUrl){
		if(StringUtils.isNotEmpty(oldUrl) && StringUtils.isNotEmpty(newUrl) && !newUrl.equals(oldUrl)){
			return delete(StringUtil.oldUrl(oldUrl));
		}
		return  false;
	}


	/**
	 * 删除本地旧图
	 * @param newUrl
	 * @param oldUrl
	 * @return boolean
	 */
	public  boolean delOldPic(String newUrl,String oldUrl){
		if(StringUtils.isNotEmpty(oldUrl) && StringUtils.isNotEmpty(newUrl) && !newUrl.equals(oldUrl)){
			File file = new File(oldUrl);
			try {
                file.delete();
            }catch (Exception e){
			    return false;
            }
            return true;
		}
		return  false;
	}


	/**
	 * 上传附件到本地
	 * @param file 文件
	 * @param request
	 * @param serverLode 所在文件夹
	 * @param folder 具体文件夹
	 * @param relativePath 是不是相对路径
	 * @return
	 * @throws IOException
	 */
	public  static ResultModel uploadFile(MultipartFile[] file, HttpServletRequest request,String serverLode, String folder, boolean relativePath) throws IOException {
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://"
				+ request.getServerName() + ":" + request.getServerPort()
				+ path + "/";

		//获得webapp所在的物理路径
		String realPath = request.getSession().getServletContext().getRealPath("/"+serverLode)+ "\\";
		String folders = "";
		if(StringUtils.isNotBlank(folder)){
			folders = folder+"\\"+ LocalDateTime.now()+"\\";
		}
		realPath = realPath+folders;
		//判断上传目录是否存在
		File files = new File(realPath);
		if (!files.exists()){
			files.mkdirs();
		}
		List<Map> listImagePath=new ArrayList<>();
		for (MultipartFile partFile:file){
			if (!partFile.isEmpty()){
				Map<String,Object> map = StringUtil.getFileName(fileName,filePath,partFile);
				String fileNames = (String) map.get(fileName);
				String filePaths = (String) map.get(filePath);
				String newFile = realPath+filePaths;
				partFile.transferTo(new File(newFile));

				LinkedHashMap<String,String> hashMap  = new LinkedHashMap<>();
				hashMap.put(fileName,fileNames);
				if(relativePath){//相对路径
					String url = basePath+serverLode+"/";
					if(StringUtils.isNotBlank(folder)){
						url += folder+"/"+ LocalDateTime.now() +"/";
					}
					hashMap.put(filePath,url+filePaths);
				}else{
					hashMap.put(filePath,newFile);
				}
				listImagePath.add(hashMap);
			}
		}

		return ResultModel.success("",listImagePath);
	}

}
